package com.soft.service;

import com.soft.dao.UserDaoImpl;
import com.soft.pojo.User;
import com.soft.utils.Result;

import java.util.ArrayList;

/**
 * @author ruoxi
 * @create 2021-12-25 15:26
 */
public class UserService {
    private UserDaoImpl userDao = new UserDaoImpl();

    public Result login(User user, String inputCode, String code) {
        if (code.equalsIgnoreCase(inputCode)) {
            if (user.getUsername() == null || "".equals(user.getUsername())) {
                return Result.me(false).setMsg("请输入用户名!");
            } else if (user.getPassword() == null || "".equals(user.getPassword())) {
                return Result.me(false).setMsg("请输入密码!");
            } else {
                User u = userDao.selectByKey(user);
                if (u != null) {
                    if (u.getPassword().equals(user.getPassword())) {
                        u.setPassword("");
                        return Result.me(u);
                    } else {
                        return Result.me(false).setMsg("密码错误！");
                    }
                } else {
                    return Result.me(false).setMsg("用户名不存在！");
                }
            }
        } else {
            return Result.me(false).setMsg("验证码输入错误");
        }
    }

    public int findUserCount() {
        return userDao.selectByAll().size();
    }

    public ArrayList<User> findUserByPage(int currentPage, int currentCount) {
        return (ArrayList<User>) userDao.selectUserByPage(currentPage, currentCount);
    }

    public Result findUserByKey(User user) {
        if (userDao.selectByKey(user) == null || user.getUsername() != null) {
            return Result.me().setMsg("用户名可以注册！");
        }else {
            return Result.me(false).setMsg("用户名已被注册");
        }
    }

    public Result addUser(User user) {
        int line = userDao.add(user);
        if (line>0) {
            return Result.me().setMsg("添加功！");
        }else {
            return Result.me(false).setMsg("添加失败！");
        }
    }

    public void removeUserById(int id) {
        userDao.del(id);
    }

    public User findUserById(int id) {
        return userDao.selectUserById(id);
    }

    public Result editUserById(User user) {
        int line = userDao.update(user);
        if (line > 0) {
            return Result.me().setMsg("修改成功！");
        }
        return Result.me(false).setMsg("修改失败");
    }
}
